package com.xyzq.hs;

import java.util.Arrays;

import com.xyzq.hs.util.ByteUtils;

public class Header {
	//header=[tag,xyzq,version,size,bodyType,checkSum]
	public final static int HEADER_SIZE=20;
	public final static int COMMAND_COUNT_SIZE=2;
	public final static short HEADER_BODYTYPE_REQUEST=1;
	public final static short HEADER_BODYTYPE_RESPONSE=2;
	private byte[] tag;
	private byte[] company;
	private byte[] version;
	private byte[] size;
	private byte[] bodyType;
	private byte[] checkSum;
	
	private int bodySize;
	
	public Header(int bodySize,short bodyType){
		this.tag = new byte[]{'F','F','F','F'};
		this.company = new byte[]{'X','Y','Z','Q'};
		this.version = new byte[]{0,0,0,1};
		this.size = ByteUtils.int2byte(bodySize+COMMAND_COUNT_SIZE);
		this.bodyType = ByteUtils.short2byte(bodyType);
		byte[] merge = ByteUtils.merge(this.tag,this.company,this.version,this.size,this.bodyType);
		this.checkSum= ByteUtils.calcCheckSum(merge);
	}
	
	public Header(byte[] header){
		this.tag = ByteUtils.subBytes(header, 0, 4);
		this.company = ByteUtils.subBytes(header, 4, 4);
		this.version = ByteUtils.subBytes(header, 8, 4);
		this.size = ByteUtils.subBytes(header, 12, 4);
		this.bodyType = ByteUtils.subBytes(header, 16, 2);
		this.checkSum = ByteUtils.subBytes(header, 18, 2);
	}
	
	public boolean validate(){
		byte[] merge = ByteUtils.merge(this.tag,this.company,this.version,this.size,this.bodyType);
		byte[] _checkSum= ByteUtils.calcCheckSum(merge);
		return Arrays.equals(this.checkSum, _checkSum);
	}
	
	public byte[] asBytes(){
		return ByteUtils.merge(this.tag,this.company,this.version,this.size,this.bodyType,this.checkSum);
	}
	
	public int getBodySize() {
		return ByteUtils.byte2int(this.size);
	}

	@Override
	public String toString() {
		return "Header [\n tag=" + Arrays.toString(tag) + ", \n company="
				+ Arrays.toString(company) + ", \n version="
				+ Arrays.toString(version) + ", \n size=" + Arrays.toString(size)
				+ ", \n bodyType=" + Arrays.toString(bodyType) + ",\n checkSum="
				+ Arrays.toString(checkSum) + ", \n bodySize=" + bodySize + " \n ]";
	}
	
	

	
	
}
